<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Requests\Permission\StorePermissionRequest;
use App\Http\Requests\Permission\UpdatePermissionRequest;
use App\Models\Permission;
use Illuminate\Http\Request;

class PermissionController extends ApiController
{
    public function __construct()
    {
        $this->authorizePermission('manage_permissions');
    }

    /**
     * 获取权限列表
     */
    public function index(Request $request)
    {
        $permissions = Permission::query()
            ->when($request->filled('name'), function ($query) use ($request) {
                $query->where('name', 'like', '%' . $request->name . '%');
            })
            ->when($request->filled('slug'), function ($query) use ($request) {
                $query->where('slug', 'like', '%' . $request->slug . '%');
            })
            ->paginate(10);

        return $this->paginate($permissions);
    }

    /**
     * 创建权限
     */
    public function store(StorePermissionRequest $request)
    {
        $data = $request->validated();
        $permission = Permission::create($data);

        return $this->success($permission, '创建成功');
    }

    /**
     * 获取权限详情
     */
    public function show(Permission $permission)
    {
        return $this->success($permission);
    }

    /**
     * 更新权限
     */
    public function update(UpdatePermissionRequest $request, Permission $permission)
    {
        $data = $request->validated();
        $permission->update($data);

        return $this->success($permission, '更新成功');
    }

    /**
     * 删除权限
     */
    public function destroy(Permission $permission)
    {
        $permission->delete();

        return $this->success(null, '删除成功');
    }
}
